package org.jugile.util;

/*

Copyright (C) 2007-2011 Jukka Rahkonen  email: jukka.rahkonen@iki.fi

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

/**
 * "And the four beasts had each of them six wings about him ; and they were 
 *  full of eyes within: and they rest not day and night, saying, 
 *  Holy, holy, holy, Lord God Almighty, which was, and is, and is to come.
 *  And when those beasts give glory and honour and thanks to him that 
 *  sat on the throne, who liveth for ever and ever." (Rev 4:8-9)
 * 
 * ==========
 * 
 * @author jukka.rahkonen@iki.fi
 */
public class DynClassLoader extends ClassLoader {

	private String pname;
    public DynClassLoader(String pname, ClassLoader parent) {
    	super(parent);
    	this.pname = pname;
    }

    public Class loadClass(String name) throws ClassNotFoundException {
    	if (!name.startsWith(pname + ".")) return super.loadClass(name);
    	String fname = name.replace('.', '/');
    	Blob b = new Blob("/" + fname + ".class");
        byte[] classData = b.getData();
        return defineClass(name, classData, 0, classData.length);
    }

    public static Object reloadInstance(String name) {
    	String pname = name.substring(0, name.lastIndexOf('.'));
    	DynClassLoader cl = new DynClassLoader(pname, DynClassLoader.class.getClassLoader());
    	try {
    		Class clazz = cl.loadClass(name);
    		return clazz.newInstance();
    	} catch (Exception e) {
    		throw new RuntimeException(e);
    	}
    }
    
}
